/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.app.web.controllers;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.app.model.entities.JmbUsers;
import org.app.model.session.JmbUsersFacade;

/**
 *
 * @author Santiago
 */
@ManagedBean
@SessionScoped
public class LoginController implements Serializable {
  
  @EJB
  private JmbUsersFacade jmbUsersFacade;
  private JmbUsers jmbUser;
  
  /**
   * Creates a new instance of LoginController
   */
  public LoginController() {
    jmbUser = new JmbUsers();
  }

  public String login() {
    JmbUsers registerUser = jmbUsersFacade.find(this.jmbUser.getUserMail());
    
    if (registerUser != null) {
      if (registerUser.getUserPassword().equals(this.jmbUser.getUserPassword())) {
        this.jmbUser.setUserJnick(registerUser.getUserJnick());
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("username", this.jmbUser.getUserJnick());
        return "index?faces-redirect=true";
      } else {
        return "login";
      }
    } else {
      return "login";
    }

  }

  public String userLogout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
  }

  /**
   * @return the jmbUser
   */
  public JmbUsers getJmbUser() {
    return jmbUser;
  }

  /**
   * @param jmbUser the jmbUser to set
   */
  public void setJmbUser(JmbUsers jmbUser) {
    this.jmbUser = jmbUser;
  }
}
